
import 'package:flutter_model_package/parse_base.dart';
import 'package:flutter_model_package/util/date_util.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

import 'Food.dart';
import 'FoodCombo.dart';
import 'FoodMenuSection.dart';

class FoodMenu extends MSParseBase {
  FoodMenu() : super("FoodMenu");
  FoodMenu.cloe() : this();

  @override
  FoodMenu clone(Map<String, dynamic> map) => FoodMenu.cloe()..fromJson(map);

  Iterable<FoodMenuSection> get sections => get<List<dynamic>>("sections").map((e) => e);

  FoodCombo get current => get<List<dynamic>>("combos").first;

  Iterable<FoodCombo> get currents => get<List<dynamic>>("combos").map((e) => e);

  QueryBuilder forDate(DateTime date) {
    return QueryBuilder.or(this, [
      QueryBuilder(this)..whereEqualTo("period", "daily"),
      QueryBuilder(this)
        ..whereEqualTo("period", "weekly")
        ..whereEqualTo("days", DateUtil.getDayOfWeek(date)),
      QueryBuilder(this)
        ..whereEqualTo("period", "monthly")
        ..whereEqualTo("days", date.day),
      QueryBuilder(this)
        ..whereEqualTo("period", "yearly")
        ..whereEqualTo("days", DateUtil.getDayOfYear(date))
    ]);
  }

  replace(FoodCombo combo, FoodMenuSection section, Food food) {
    String code = combo.get("code");
    var next = code
        .split("|")
        .map((sub) {
      List list = sub.split(":");
      var sid = list[0];
      var fid = list[1];
      if (sid == section.objectId) {
        if (food != null) return "$sid:${food.objectId}";
        return "";
      }
      return sub;
    })
        .toList()
        .where((element) => element.length > 0)
        .join("|");
    if (next == code) return combo;
    return this.currents.firstWhere((e) => e.get("code") == next);
  }
}